package io.itit.ecp.admin.file.action;


import io.itit.ecp.admin.file.FileUploadResult;
import io.itit.ecp.admin.file.service.FileService;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.utils.CommonUtils;
import io.itit.grass.common.utils.ImageConvertBase64;
import io.itit.grass.common.utils.ImageSchemeMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@Api(tags = {"文件管理"})
@RequiredArgsConstructor
@RequestMapping({"/grass-file/file"})
public class FileController {

    private final FileService fileService;

    @ApiOperation("上传文件")
    @PostMapping({"upload"})
    public ResultResp<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        FileUploadResult result = fileService.upload(file);
        return ResultResp.success(result.getUrl());
    }

    @ApiOperation("上传文件base64")
    @PostMapping({"uploadBase64"})
    public ResultResp<String> upload(@RequestParam("file") @RequestBody String base64) throws IOException {
        String id = CommonUtils.getUUID();
        ImageSchemeMapper.Extension extension = ImageSchemeMapper.getExtensionFromImageBase64(base64);
        String filename = id + "." + extension.getExt();
        byte[] bytes = ImageConvertBase64.toBytes(base64);
        FileUploadResult result = fileService.upload(bytes, filename, extension.getContentType());
        return ResultResp.success(result.getUrl());
    }
}
